#ifndef __UDP_SERVER__
#define __UDP_SERVER__

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>

#include "Log.hpp"
#include "dict.hpp"
enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    RECV_ERROR,
    ARGU_ERROR
};

using func_t = std::function<std::string (std::string)>;

const std::string serverip = "0.0.0.0";
const uint16_t defaultport = 8080;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func) : _port(port), _func(func)
    {
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "create socket fail, exit code : %d\n", SOCK_ERROR);
        }
        LOG(INFO, "create socket success\n");

        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(server);

        int n = bind(_sockfd, (sockaddr *)&server, len);
        if (n < 0)
        {
            LOG(FATAL, "bind fail, exit code : %d\n", BIND_ERROR);
        }
        LOG(INFO, "bind success\n");
    }

    void Start()
    {
        char buffer[1024];

        while (true)
        {
            sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t plen = sizeof(peer);

            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &plen);

            if (n < 0)
            {
                LOG(ERROR, "recv fail, exit code : %d", RECV_ERROR);
            }
            else if (n > 0)
            {
                buffer[n] = 0;
                LOG(DEBUG, "server receive a query# what's %s in chinese? ", buffer);

                std::string chinese = _func(std::string(buffer));

                sendto(_sockfd, chinese.c_str(), chinese.size(), 0, (sockaddr *)&peer, plen);
            }
            else if (n == 0)
            {
                break;
            }
        }
    }

private:
    int _sockfd;
    uint16_t _port;

    func_t _func;
};

#endif